import Mock from 'mockjs';
import fetchMock from 'fetch-mock';
import { sleep } from './';

export const Random = Mock.Random;

// 创建模拟数据
const toData = (data?: any, length?: number | string) => async () => {
  await sleep(Random.natural(300, 1000)); // 随机暂停时间
  return Mock.mock({
    code: 0,
    msg: '模拟数据',
    [length ? `data|${length}` : 'data']: length ? [data] : data,
  });
};

// 创建模拟器
export default (baseURL: string) => {
  // 加入基础地址
  const toUrl = (url: string) => new RegExp(baseURL + url);

  // 链式操作
  const mock = {
    get: (url: string, data?: any, length?: number | string) => {
      fetchMock.get(toUrl(url), toData(data, length));
      return mock;
    },
    post: (url: string, data?: any, length?: number | string) => {
      fetchMock.post(toUrl(url), toData(data, length));
      return mock;
    },
  };
  return mock;
};
